<template>
	<view class="forgot-password-container">
		<!-- 自定义导航栏 -->
		<ob-navbar 
			title="找回密码"
			:show-back="true"
			background-color="rgba(255, 255, 255, 0.95)"
			title-color="#333333"
			:border="true"
			:prevent-default-back="true"
			@left-click="handleBackToLogin"
		/>
		
		
		<!-- 主要内容区域 -->
		<view class="content-wrapper">
			<!-- 头部说明 -->
			<view class="header-section">
				<view class="icon-wrapper">
					<text class="lock-icon">🔐</text>
				</view>
				<text class="main-title">找回密码</text>
				<text class="desc-text">{{ currentStep === 1 ? '请输入您的邮箱地址，我们将发送验证码到您的邮箱' : '请输入您收到的验证码和新密码' }}</text>
			</view>
			
			<!-- 步骤指示器 -->
			<view class="step-indicator">
				<view class="step-item" :class="{ 'step-active': currentStep >= 1, 'step-completed': currentStep > 1 }">
					<view class="step-circle">
						<text class="step-number">{{ currentStep > 1 ? '✓' : '1' }}</text>
					</view>
					<text class="step-label">验证邮箱</text>
				</view>
				<view class="step-line" :class="{ 'line-active': currentStep > 1 }"></view>
				<view class="step-item" :class="{ 'step-active': currentStep >= 2 }">
					<view class="step-circle">
						<text class="step-number">2</text>
					</view>
					<text class="step-label">重置密码</text>
				</view>
			</view>
			
			<!-- 表单区域 -->
			<view class="form-section">
				<view class="form-container">
					<!-- 第一步：邮箱验证 -->
					<view v-if="currentStep === 1" class="step-content">
						<view class="input-group">
							<view class="input-label">
								<text class="label-text">邮箱地址</text>
								<text class="required-mark">*</text>
							</view>
							<view class="input-wrapper" :class="{ 'input-error': errors.email }">
								<text class="input-icon">📧</text>
								<input 
									class="input-field"
									type="text"
									v-model="formData.email"
									placeholder="请输入注册时使用的邮箱"
									@blur="validateEmail"
									@input="clearError('email')"
								/>
							</view>
							<text v-if="errors.email" class="error-text">{{ errors.email }}</text>
						</view>
						
						<button 
							class="submit-btn"
							:class="{ 'btn-disabled': !canSendCode }"
							:disabled="!canSendCode"
							@click="sendVerificationCode"
						>
							<text class="btn-text">{{ isLoading ? '发送中...' : '发送验证码' }}</text>
						</button>
					</view>
					
					<!-- 第二步：验证码和新密码 -->
					<view v-if="currentStep === 2" class="step-content">
						<!-- 验证码输入 -->
						<view class="input-group">
							<view class="input-label">
								<text class="label-text">验证码</text>
								<text class="required-mark">*</text>
							</view>
							<view class="verification-wrapper">
								<view class="input-wrapper" :class="{ 'input-error': errors.code }">
									<text class="input-icon">🔢</text>
									<input 
										class="input-field"
										type="number"
										v-model="formData.code"
										placeholder="请输入6位验证码"
										maxlength="6"
										@blur="validateCode"
										@input="clearError('code')"
									/>
								</view>
								<button 
									class="resend-btn"
									:class="{ 'btn-disabled': countdown > 0 }"
									:disabled="countdown > 0"
									@click="resendCode"
								>
									<text class="resend-text">
										{{ countdown > 0 ? `${countdown}s后重发` : '重新发送' }}
									</text>
								</button>
							</view>
							<text v-if="errors.code" class="error-text">{{ errors.code }}</text>
						</view>
						
						<!-- 新密码输入 -->
						<view class="input-group">
							<view class="input-label">
								<text class="label-text">新密码</text>
								<text class="required-mark">*</text>
							</view>
							<view class="input-wrapper" :class="{ 'input-error': errors.newPassword }">
								<text class="input-icon">🔒</text>
								<input 
									class="input-field"
									:type="showNewPassword ? 'text' : 'password'"
									v-model="formData.newPassword"
									placeholder="请输入新密码（8-20位）"
									@blur="validateNewPassword"
									@input="clearError('newPassword')"
								/>
								<text class="toggle-password" @click="toggleNewPassword">
									{{ showNewPassword ? '👁️' : '👁️‍🗨️' }}
								</text>
							</view>
							<text v-if="errors.newPassword" class="error-text">{{ errors.newPassword }}</text>
						</view>
						
						<!-- 确认新密码输入 -->
						<view class="input-group">
							<view class="input-label">
								<text class="label-text">确认新密码</text>
								<text class="required-mark">*</text>
							</view>
							<view class="input-wrapper" :class="{ 'input-error': errors.confirmNewPassword }">
								<text class="input-icon">🔒</text>
								<input 
									class="input-field"
									:type="showConfirmNewPassword ? 'text' : 'password'"
									v-model="formData.confirmNewPassword"
									placeholder="请再次输入新密码"
									@blur="validateConfirmNewPassword"
									@input="clearError('confirmNewPassword')"
								/>
								<text class="toggle-password" @click="toggleConfirmNewPassword">
									{{ showConfirmNewPassword ? '👁️' : '👁️‍🗨️' }}
								</text>
							</view>
							<text v-if="errors.confirmNewPassword" class="error-text">{{ errors.confirmNewPassword }}</text>
						</view>
						
						<button 
							class="submit-btn"
							:class="{ 'btn-disabled': !canResetPassword }"
							:disabled="!canResetPassword"
							@click="resetPassword"
						>
							<text class="btn-text">{{ isLoading ? '重置中...' : '重置密码' }}</text>
						</button>
					</view>
				</view>
			</view>
			
			<!-- 提示信息 -->
			<view class="tips-section">
				<view class="tips-card">
					<text class="tips-title">💡 温馨提示</text>
					<text class="tips-text" v-if="currentStep === 1">
						• 请确保输入的邮箱地址正确\n
						• 验证码有效期为10分钟\n
						• 如未收到邮件，请检查垃圾邮件箱
					</text>
					<text class="tips-text" v-else>
						• 新密码长度为8-20位，需包含字母和数字\n
						• 请妥善保管您的新密码\n
						• 重置成功后请使用新密码登录
					</text>
				</view>
			</view>
			
			<!-- 底部链接 -->
			<view class="footer-section">
				<text class="footer-text">想起密码了？</text>
				<text class="footer-link" @click="goToLogin">返回登录</text>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" :text="loadingText" />
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { validateEmail as validateEmailUtil, validatePassword as validatePasswordUtil } from '../../utils/common.js'
import authApi from '../../api/auth.js'

// 响应式数据
const currentStep = ref(1)
const formData = ref({
	email: '',
	code: '',
	newPassword: '',
	confirmNewPassword: ''
})

const errors = ref({})
const showNewPassword = ref(false)
const showConfirmNewPassword = ref(false)
const isLoading = ref(false)
const countdown = ref(0)
let countdownTimer = null

// 计算属性
const loadingText = computed(() => {
	if (currentStep.value === 1) {
		return '发送验证码中...'
	} else {
		return '重置密码中...'
	}
})

const canSendCode = computed(() => {
	return formData.value.email && 
		   !errors.value.email && 
		   !isLoading.value
})

const canResetPassword = computed(() => {
	return formData.value.code &&
		   formData.value.newPassword &&
		   formData.value.confirmNewPassword &&
		   !errors.value.code &&
		   !errors.value.newPassword &&
		   !errors.value.confirmNewPassword &&
		   !isLoading.value
})

// 页面加载时检查URL参数
onMounted(() => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const options = currentPage.options
	
	if (options.email) {
		formData.value.email = decodeURIComponent(options.email)
	}
})

// 页面卸载时清除定时器
onUnmounted(() => {
	if (countdownTimer) {
		clearInterval(countdownTimer)
	}
})

// 表单验证方法
const validateEmail = () => {
	if (!formData.value.email) {
		errors.value.email = '请输入邮箱地址'
		return false
	}
	if (!validateEmailUtil(formData.value.email)) {
		errors.value.email = '请输入有效的邮箱地址'
		return false
	}
	delete errors.value.email
	return true
}

const validateCode = () => {
	if (!formData.value.code) {
		errors.value.code = '请输入验证码'
		return false
	}
	if (formData.value.code.length !== 6) {
		errors.value.code = '请输入6位验证码'
		return false
	}
	delete errors.value.code
	return true
}

const validateNewPassword = () => {
	if (!formData.value.newPassword) {
		errors.value.newPassword = '请输入新密码'
		return false
	}
	if (!validatePasswordUtil(formData.value.newPassword)) {
		errors.value.newPassword = '密码长度应为8-20位，包含字母和数字'
		return false
	}
	delete errors.value.newPassword
	
	// 如果确认密码已输入，重新验证确认密码
	if (formData.value.confirmNewPassword) {
		validateConfirmNewPassword()
	}
	return true
}

const validateConfirmNewPassword = () => {
	if (!formData.value.confirmNewPassword) {
		errors.value.confirmNewPassword = '请确认新密码'
		return false
	}
	if (formData.value.newPassword !== formData.value.confirmNewPassword) {
		errors.value.confirmNewPassword = '两次输入的密码不一致'
		return false
	}
	delete errors.value.confirmNewPassword
	return true
}

// 清除错误信息
const clearError = (field) => {
	if (errors.value[field]) {
		delete errors.value[field]
	}
}

// 切换密码显示
const toggleNewPassword = () => {
	showNewPassword.value = !showNewPassword.value
}

const toggleConfirmNewPassword = () => {
	showConfirmNewPassword.value = !showConfirmNewPassword.value
}

// 倒计时功能
const startCountdown = (seconds = 60) => {
	countdown.value = seconds
	countdownTimer = setInterval(() => {
		countdown.value--
		if (countdown.value <= 0) {
			clearInterval(countdownTimer)
			countdownTimer = null
		}
	}, 1000)
}

// 发送验证码
const sendVerificationCode = async () => {
	if (!validateEmail()) {
		return
	}
	
	try {
		isLoading.value = true
		
		await authApi.forgotPassword({
			email: formData.value.email
		})
		
		uni.showToast({
			title: '验证码已发送到您的邮箱',
			icon: 'success',
			duration: 2000
		})
		
		// 切换到第二步
		currentStep.value = 2
		startCountdown(60)
		
	} catch (error) {
		console.error('发送验证码失败:', error)
		
		// 处理特定的错误情况
		let errorMessage = '发送失败，请重试'
		if (error.message) {
			if (error.message.includes('邮箱不存在') || error.message.includes('not found')) {
				errorMessage = '该邮箱未注册，请检查邮箱地址'
			} else {
				errorMessage = error.message
			}
		}
		
		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 2000
		})
	} finally {
		isLoading.value = false
	}
}

// 重新发送验证码
const resendCode = async () => {
	try {
		await authApi.forgotPassword({
			email: formData.value.email
		})
		
		uni.showToast({
			title: '验证码已重新发送',
			icon: 'success',
			duration: 2000
		})
		
		startCountdown(60)
		
	} catch (error) {
		console.error('重新发送验证码失败:', error)
		
		// 处理特定的错误情况
		let errorMessage = '发送失败，请重试'
		if (error.message) {
			if (error.message.includes('邮箱不存在') || error.message.includes('not found')) {
				errorMessage = '该邮箱未注册，请检查邮箱地址'
			} else {
				errorMessage = error.message
			}
		}
		
		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 2000
		})
	}
}

// 重置密码
const resetPassword = async () => {
	// 验证所有字段
	const isCodeValid = validateCode()
	const isNewPasswordValid = validateNewPassword()
	const isConfirmNewPasswordValid = validateConfirmNewPassword()
	
	if (!isCodeValid || !isNewPasswordValid || !isConfirmNewPasswordValid) {
		return
	}
	
	try {
		isLoading.value = true
		
		await authApi.resetPassword({
			email: formData.value.email,
			code: formData.value.code,
			newPassword: formData.value.newPassword
		})
		
		uni.showToast({
			title: '密码重置成功！',
			icon: 'success',
			duration: 2000
		})
		
		// 重置成功后跳转到登录页面
		setTimeout(() => {
			uni.reLaunch({
				url: '/pages/auth/login'
			})
		}, 2000)
		
	} catch (error) {
		console.error('重置密码失败:', error)
		
		// 处理特定的错误情况
		let errorMessage = '重置失败，请重试'
		if (error.message) {
			if (error.message.includes('验证码错误') || error.message.includes('invalid code')) {
				errorMessage = '验证码错误，请重新输入'
			} else if (error.message.includes('验证码过期') || error.message.includes('expired')) {
				errorMessage = '验证码已过期，请重新发送'
			} else {
				errorMessage = error.message
			}
		}
		
		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 2000
		})
	} finally {
		isLoading.value = false
	}
}


// 页面跳转
const goToLogin = () => {
	// 优先尝试返回上一页（如果上一页是登录页）
	uni.navigateBack({
		fail: () => {
			// 如果无法返回，则重定向到登录页
			uni.redirectTo({
				url: '/pages/auth/login'
			})
		}
	})
}

// 返回登录页面
const handleBackToLogin = () => {
	uni.redirectTo({
		url: '/pages/auth/login'
	})
}
</script>

<style lang="scss" scoped>
.forgot-password-container {
	min-height: 100vh;
	background: #ffffff;
	position: relative;
	overflow: hidden;
}


.content-wrapper {
	position: relative;
	z-index: 1;
	padding: 100px 30px 40px;
}

.header-section {
	text-align: center;
	margin-bottom: 30px;
	
	.icon-wrapper {
		width: 80px;
		height: 80px;
		background: rgba(0, 0, 0, 0.05);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 20px;
		border: 1px solid rgba(0, 0, 0, 0.1);
		
		.lock-icon {
			font-size: 36px;
		}
	}
	
	.main-title {
		display: block;
		font-size: 28px;
		font-weight: bold;
		color: var(--text-color);
		margin-bottom: 12px;
	}
	
	.desc-text {
		display: block;
		font-size: 16px;
		color: var(--text-secondary);
		line-height: 1.5;
		padding: 0 10px;
	}
}

.step-indicator {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 30px;
}

.step-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	opacity: 0.5;
	transition: opacity 0.3s ease;
	
	&.step-active {
		opacity: 1;
	}
	
	&.step-completed {
		opacity: 1;
	}
}

.step-circle {
	width: 40px;
	height: 40px;
	background: rgba(0, 0, 0, 0.1);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 8px;
	transition: all 0.3s ease;
	border: 1px solid rgba(0, 0, 0, 0.15);
	
	.step-active & {
		background: var(--primary-color);
		border-color: var(--primary-color);
		
		.step-number {
			color: #FFFFFF;
		}
	}
	
	.step-completed & {
		background: #4CAF50;
		border-color: #4CAF50;
	}
	
	.step-number {
		font-size: 16px;
		font-weight: bold;
		color: var(--text-secondary);
	}
}

.step-label {
	font-size: 14px;
	color: var(--text-secondary);
}

.step-line {
	width: 60px;
	height: 2px;
	background: rgba(0, 0, 0, 0.15);
	margin: 0 20px;
	transition: background 0.3s ease;
	
	&.line-active {
		background: var(--primary-color);
	}
}

.form-section {
	margin-bottom: 30px;
}

.form-container {
	background: rgba(255, 255, 255, 0.95);
	border-radius: 20px;
	padding: 30px 25px;
	backdrop-filter: blur(10px);
}

.step-content {
	animation: fadeIn 0.5s ease-in-out;
}

.input-group {
	margin-bottom: 20px;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.input-label {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
	
	.label-text {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
	}
	
	.required-mark {
		color: #ff4757;
		margin-left: 4px;
	}
}

.input-wrapper {
	display: flex;
	align-items: center;
	background: #f8f9fa;
	border: 2px solid transparent;
	border-radius: 12px;
	padding: 0 16px;
	transition: all 0.3s ease;
	
	&:focus-within {
		border-color: var(--primary-color);
		background: #FFFFFF;
	}
	
	&.input-error {
		border-color: #ff4757;
		background: #fff5f5;
	}
}

.input-icon {
	font-size: 18px;
	margin-right: 12px;
	opacity: 0.6;
}

.input-field {
	flex: 1;
	height: 50px;
	font-size: 16px;
	color: #333333;
	background: transparent;
	border: none;
	outline: none;
}

.toggle-password {
	font-size: 18px;
	padding: 5px;
	cursor: pointer;
	opacity: 0.6;
	transition: opacity 0.3s ease;
	
	&:hover {
		opacity: 1;
	}
}

.verification-wrapper {
	display: flex;
	gap: 10px;
	
	.input-wrapper {
		flex: 1;
	}
}

.resend-btn {
	width: 100px;
	height: 50px;
	background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
	border: none;
	border-radius: 12px;
	transition: all 0.3s ease;
	box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
	
	&:hover {
		background: linear-gradient(135deg, #0051D5 0%, #003A9B 100%);
		transform: translateY(-1px);
		box-shadow: 0 6px 16px rgba(0, 122, 255, 0.4);
	}
	
	&.btn-disabled {
		background: #ddd;
		cursor: not-allowed;
		box-shadow: none;
		transform: none;
	}
	
	.resend-text {
		font-size: 14px;
		color: #FFFFFF;
		font-weight: 500;
	}
}

.error-text {
	display: block;
	font-size: 14px;
	color: #ff4757;
	margin-top: 6px;
	margin-left: 4px;
}

.submit-btn {
	width: 100%;
	height: 50px;
	background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
	border: none;
	border-radius: 12px;
	margin-top: 20px;
	transition: all 0.3s ease;
	box-shadow: 0 6px 20px rgba(0, 122, 255, 0.3);
	
	&:hover {
		background: linear-gradient(135deg, #0051D5 0%, #003A9B 100%);
		transform: translateY(-1px);
		box-shadow: 0 8px 24px rgba(0, 122, 255, 0.4);
	}
	
	&.btn-disabled {
		background: #ddd;
		cursor: not-allowed;
		box-shadow: none;
		transform: none;
	}
	
	.btn-text {
		font-size: 18px;
		font-weight: 600;
		color: #FFFFFF;
	}
}

.tips-section {
	margin-bottom: 30px;
}

.tips-card {
	background: rgba(0, 0, 0, 0.03);
	border-radius: 16px;
	padding: 20px;
	border: 1px solid rgba(0, 0, 0, 0.1);
	backdrop-filter: blur(10px);
	
	.tips-title {
		display: block;
		font-size: 16px;
		font-weight: 600;
		color: var(--text-color);
		margin-bottom: 12px;
	}
	
	.tips-text {
		font-size: 14px;
		color: var(--text-secondary);
		line-height: 1.6;
		white-space: pre-line;
	}
}

.footer-section {
	text-align: center;
	
	.footer-text {
		font-size: 16px;
		color: var(--text-secondary);
	}
	
	.footer-link {
		font-size: 16px;
		color: var(--primary-color);
		font-weight: 600;
		margin-left: 8px;
		text-decoration: underline;
	}
}

@keyframes float {
	0%, 100% {
		transform: translateY(0px);
	}
	50% {
		transform: translateY(-15px);
	}
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(20px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}
</style>